package org.langcom;

import java.util.Stack;

public class ThreadClassLoaderManager {

	private static final ThreadLocal<Stack<ClassLoader>> classLoaderStack = new ThreadLocal<Stack<ClassLoader>>();

	private ThreadClassLoaderManager() {
	}

	public static ClassLoader saveContextClassLoader() {
		ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
		getStack().push(contextClassLoader);
		return contextClassLoader;
	}

	private static Stack<ClassLoader> getStack() {
		Stack<ClassLoader> stack = classLoaderStack.get();
		if (stack == null) {
			stack = new Stack<ClassLoader>();
			classLoaderStack.set(stack);
		}
		return stack;
	}

	public static ClassLoader setContextClassLoader(Class clazz) {
		return setContextClassLoader(clazz.getClassLoader());
	}

	public static ClassLoader setContextClassLoader(ClassLoader newClassLoader) {
		try {
			return saveContextClassLoader();
		} finally {
			Thread.currentThread().setContextClassLoader(newClassLoader);
		}
	}

	public static void restoreContextClassLoader() {
		if (!getStack().isEmpty()) {
			Thread.currentThread().setContextClassLoader(getStack().pop());
		}
	}

}
